import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioDemo extends StatefulWidget {
  const DioDemo({super.key});

  @override
  State<DioDemo> createState() => _DioDemoState();
}

class _DioDemoState extends State<DioDemo> {
  List _channels = [];

  @override
  void initState() {
    super.initState();
    _getData();
  }

  _getData() async {
    // 1. 创建dio实例
    Dio dio = Dio();

    // 2. 发送请求
    final res = await dio.get('https://geek.itheima.net/v1_0/channels');
    // 4. 处理响应
    _channels = res.data['data']['channels'];
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
      ),
      itemBuilder: (context, index) {
        return Container(
          alignment: Alignment.center,
          color: Colors.purple,
          child: Text(
            _channels[index]['name'],
            style: const TextStyle(color: Colors.white, fontSize: 16),
          ),
        );
      },
      itemCount: _channels.length,
    );
  }
}
